<template>
  <div>
    <!-- QuillEditor 组件 -->
    <QuillEditor ref="myQuillEditor"
                 theme="snow"
                 v-model:content="content"
                 :options="data.editorOption"
                 contentType="html"
                 @update:content="setValue()"
    />
    <!-- 自定义图片上传 -->
    <input type="file" hidden accept=".jpg,.png" ref="fileBtn" @change="handleUpload" />

    <!-- 实时显示富文本内容 -->
    <div class="preview" v-html="content"></div>
  </div>
</template>

<script setup>
import {QuillEditor} from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import {onMounted, reactive, ref, toRaw, watch} from 'vue'

const props = defineProps(['value'])
const emit = defineEmits(['updateValue'])
const content = ref('')
const myQuillEditor = ref()

// 工具栏按钮的选择器和对应的title
const titleConfig = ref([
  { Choice: '.ql-bold', title: '加粗' },
  { Choice: '.ql-italic', title: '斜体' },
  { Choice: '.ql-underline', title: '下划线' },
  { Choice: '.ql-header', title: '段落格式' },
  { Choice: '.ql-strike', title: '删除线' },
  { Choice: '.ql-blockquote', title: '块引用' },
  { Choice: '.ql-code', title: '插入代码' },
  { Choice: '.ql-code-block', title: '插入代码段' },
  { Choice: '.ql-font', title: '字体' },
  { Choice: '.ql-size', title: '字体大小' },
  { Choice: '.ql-list[value="ordered"]', title: '编号列表' },
  { Choice: '.ql-list[value="bullet"]', title: '项目列表' },
  { Choice: '.ql-direction', title: '文本方向' },
  { Choice: '.ql-header[value="1"]', title: 'h1标题' },
  { Choice: '.ql-header[value="2"]', title: 'h2标题' },
  { Choice: '.ql-align', title: '对齐方式' },
  { Choice: '.ql-color', title: '字体颜色' },
  { Choice: '.ql-background', title: '背景颜色' },
  { Choice: '.ql-image', title: '图像' },
  { Choice: '.ql-video', title: '视频' },
  { Choice: '.ql-formula', title: '插入公式' },
  { Choice: '.ql-clean', title: '清除字体格式' },
  { Choice: '.ql-script[value="sub"]', title: '下标' },
  { Choice: '.ql-script[value="super"]', title: '上标' },
  { Choice: '.ql-indent[value="-1"]', title: '向左缩进' },
  { Choice: '.ql-indent[value="+1"]', title: '向右缩进' },
  { Choice: '.ql-header .ql-picker-label', title: '标题大小' },
  { Choice: '.ql-align .ql-picker-item:first-child', title: '居左对齐' },
  { Choice: '.ql-align .ql-picker-item[data-value="center"]', title: '居中对齐' },
  { Choice: '.ql-align .ql-picker-item[data-value="right"]', title: '居右对齐' },
  { Choice: '.ql-align .ql-picker-item[data-value="justify"]', title: '两端对齐' }
])

// 监听回显
watch(() => props.value, (val) => {
  toRaw(myQuillEditor.value).setHTML(val)
}, { deep: true })

const fileBtn = ref()
const data = reactive({
  content: '',
  editorOption: {
    modules: {
      toolbar: [
        ['bold', 'italic', 'underline', 'strike'],
        [{ 'size': ['small', false, 'large', 'huge'] }],
        // [{ size: ['small', false, 'large', 'huge'] }], // 字体大小选项
        [{ 'color': [] }, { 'background': [] }],
        [{ 'align': [] }],
        [{ 'list': 'ordered' }, { 'list': 'bullet' }],
        [{ 'indent': '-1' }, { 'indent': '+1' }],
        [{ 'header': 1 }, { 'header': 2 }],
        ['image', 'video'], // 上传图片、上传视频
        ['clean']
      ]
    },
    placeholder: '请输入内容...'
  }
})

// 图片上传逻辑
const imgHandler = (state) => {
  if (state) {
    fileBtn.value.click()
  }
}

// // 抛出更改内容
// const setValue = () => {
//   const text = toRaw(myQuillEditor.value).getHTML()
// }

// 实时更新内容方法
const setValue = () => {
  // 可以在这里做其他操作，例如对内容进行预处理
  const quill = toRaw(myQuillEditor.value).getQuill()
  const contentHTML = quill.root.innerHTML // 将编辑器内容转换为HTML
  const fontSize = window.getComputedStyle(quill.root).fontSize // 获取字体大小
  console.log(fontSize)
  content.value = contentHTML

  // 动态更新预览区域的字体大小
  const preview = document.querySelector('.preview')
  if (preview) {
    preview.style.fontSize = fontSize
  }
}





const handleUpload = (e) => {
  const files = Array.prototype.slice.call(e.target.files)
  if (!files) {
    return
  }
  const formdata = new FormData()
  formdata.append('file', files[0])
  backsite.uploadFile(formdata)
      .then(res => {
        if (res.data.url) {
          const quill = toRaw(myQuillEditor.value).getQuill()
          const length = quill.getSelection().index
          quill.insertEmbed(length, 'image', res.data.url)
          quill.setSelection(length + 1)
        }
      })
}

// 监听工具栏的DOM变动，并添加title
const addToolbarTitles = () => {
  titleConfig.value.forEach(item => {
    const button = document.querySelector(item.Choice)
    if (button) {
      button.setAttribute('title', item.title)
    }
  })
}

// 初始化编辑器并添加title
onMounted(() => {
  const quill = toRaw(myQuillEditor.value).getQuill()

  if (myQuillEditor.value) {
    quill.getModule('toolbar').addHandler('image', imgHandler)
  }

  // 使用 MutationObserver 监听工具栏DOM是否完成加载
  // MutationObserver 可以自动监听 DOM 结构的变化，包括节点的添加、删除、属性的变化等。
  // 相比手动监控或轮询，MutationObserver 能实时响应，减少手动查询 DOM 的复杂性和性能开销。
  const toolbar = document.querySelector('.ql-toolbar')
  if (toolbar) {
    const observer = new MutationObserver(() => {
      addToolbarTitles() // 工具栏元素加载完成后，添加title
    })

    observer.observe(toolbar, { childList: true, subtree: true })

    // 手动调用，确保初次加载时添加 title
    addToolbarTitles()
  }
})


</script>

<style lang="scss">

.ql-editor {
  box-sizing: border-box;
  line-height: 1.42;
  height: 280px;
  outline: none;
  overflow-y: auto;
  padding: 12px 15px;
  tab-size: 4;
  -moz-tab-size: 4;
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.ql-snow .ql-picker.ql-size .ql-picker-label::before,
.ql-snow .ql-picker.ql-size .ql-picker-item::before {
  content: '14';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=small]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=small]::before {
  content: '10';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=large]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=large]::before {
  content: '18';
}
.ql-snow .ql-picker.ql-size .ql-picker-label[data-value=huge]::before,
.ql-snow .ql-picker.ql-size .ql-picker-item[data-value=huge]::before {
  content: '32';
}

.ql-size-small{
  font-size: 10px;
}
.ql-size-large{
  font-size: 18px;
}
.ql-size-huge{
  font-size: 32px;
}

.preview {
  margin-top: 20px;
  //padding: 10px;
  border: 1px solid #ccc;
  min-height: 100px;
  background-color: #fafafa;
  //white-space: pre-wrap; /* 保留换行 */
  ////line-height: 1.42; /* 设置一致的行高 */

  box-sizing: border-box;
  line-height: 1.42;
  height: 280px;
  outline: none;
  overflow-y: auto;
  padding: 12px 15px;
  tab-size: 4;
  -moz-tab-size: 4;
  text-align: left;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.preview p {
  margin: 0;
  padding: 0;
}

</style>
